const initState = {
  carList: []
}

const carReducer = (state = initState, action) => {
  const { type, payload } = action;
  // 设置 初始化数据
  if (type === 'initCarList') {
    return {
      ...state,
      carList: payload
    }
  }
  // 数量+
  if (type === 'addCount') {
    // payload => 项目
    const newCarList = [...state.carList];
    const item = newCarList.find(v => v.id === payload.id)
    // count++
    item.count = item.count + 1
    return {
      ...state,
      carList: newCarList
    }
  }
  // 数量-
  if (type === 'subCount') {
    // payload => 项目
    const newCarList = [...state.carList];
    const item = newCarList.find(v => v.id === payload.id)
    // count++
    item.count = item.count - 1
    return {
      ...state,
      carList: newCarList
    }
  }

  // 删除
  if (type === 'delCar') {
    const newList = state.carList.filter(v => v.id !== payload.id);

    return {
      ...state,
      carList: newList
    }
  }
  // 单选
  if (type === 'oneCheck') {
    // payload => 项目

    const newCarList = [...state.carList];

    const item = newCarList.find(v => v.id === payload.id)
    // 取返
    item.check = !item.check

    return {
      ...state,
      carList: newCarList
    }
  }
  // 全选
  if (type === 'allCheck') {
    // payload => 布尔值
    const newCarList = [...state.carList];
    newCarList.forEach(v => {
      v.check = payload
    })
    return {
      ...state,
      carList: newCarList
    }
  }
  return state
}

export default carReducer